<?php
class DeploysController extends AppController {
	public $name = 'Deploys';
	public $uses=array('Deploy','Host','SourceControl');
	
	
	function admin_index_forwindow($tid=0){
		
		
		//get filter field		
		$tid=intval($tid);
		if($tid>0){
			//clear
			$this->Session->delete($this->uses[0].'.host_id');
		}
		if($tid==0)$tid=intval($this->Session->read($this->uses[0].'.task_id'));
		
		$taskInfo=$this->getPermission($tid);
		
		if(empty($taskInfo)){
			$this->Session->write('error',_resource('you have not permission',true));
			if($this->Session->read('CurrentModule')=='Task')
				$this->redirectAjaxTo('tasks/lists','listContent');
			else
				$this->redirectAjaxTo('homes/lists','listContent');
		}
		$this->Session->write($this->uses[0].'.task_id',$tid);  
		$repoFiles=array();
		//get source control
		$sc=$this->SourceControl->find('first',array('conditions'=>array('project_id'=>$taskInfo['Project']['Project']['id'],'active'=>1)));
		if(!empty($sc)){
			//$reval=shell_exec('~/svn_search.sh '.$taskInfo['Task']['Task']['taskcode'].' https://itk-taskman.googlecode.com/svn/ ./repo/itk-taskman duyhph@gmail.com');
			$repoPath='./repo/'.$taskInfo['Project']['Project']['code'];
			//$reval=shell_exec('~/svn_search.sh '.$taskInfo['Task']['Task']['taskcode'].' '.$sc['SourceControl']['url'].' '.$repoPath.' --username '.$sc['SourceControl']['username']);
			//t('~/svn_search.sh '.$taskInfo['Task']['Task']['taskcode'].' '.$sc['SourceControl']['url'].' '.$repoPath.' --username '.$sc['SourceControl']['username']);
			$reval=shell_exec('svn checkout --force-interactive -q '.$sc['SourceControl']['url'].' '.$repoPath.' --username '.$sc['SourceControl']['username']);
			if(!empty($reval)){
				t($reval);
			}
			$reval=shell_exec('svn log '.$sc['SourceControl']['url'].' -v');
			$versions=explode("------------------------------------------------------------------------",$reval);
			if(count($versions)>0){
				foreach($versions as $k=>$ver){
					$lines=explode("\n",$ver);
					if(count($lines)>6){
						
						$commentline=$lines[count($lines)-2];
						$spacePos=strpos($commentline," ");
						if($spacePos!==false){
							$commentline=substr($commentline,0,$spacePos);
						}
						//t($commentline,0);
						if($commentline==$taskInfo['Task']['Task']['taskcode']){
							for($i=3;$i<count($lines)-3;$i++){
								$lineInfos=explode(" ",$lines[$i]);								
								//get latest version:
								$latest=shell_exec('svn info '.$repoPath.$lineInfos[4].' | findstr "Rev:"');								
								$latest=substr($latest, strrpos($latest, " ")+1);
								$latest=str_replace("\n", '', $latest);
								//get current version:
								$current=substr($lines[1], 0,strpos($lines[1], " "));
								$current=str_replace('r', '', $current);
								$repoFiles[]=$lineInfos[4].':'.$lineInfos[3].':'.$current.':'.$latest;
							}
						}
					}
				}
			}


						$files=array();
			foreach($repoFiles as $k=>$v){
				$fileinfo=explode(":",$v);
				//check if file is directory:
				//t($repoPath.$fileinfo,0);
				//t(is_dir($repoPath.$fileinfo[0]));
				if(count($fileinfo)==4 && !array_key_exists($fileinfo[0],$files) && !is_dir($repoPath.$fileinfo[0])){
					$files[$fileinfo[0]]=$fileinfo;
				}
			}
			$this->Session->write('filedeploys',$files);
			//get host
			$hosts=$this->Host->find('all',array('conditions'=>'Host.published = 1 and Host.project_id ='.$taskInfo['Project']['Project']['id']));
			//check permit
			if(!empty($hosts)){
			foreach($hosts as $k=>$v){		
				if($v['Host']['user_id']== $this->user['id'] || $this->checkUserInString($v['Host']['users']))
					$hosts[$v['Host']['id']]=$v['Host']['name'];
				unset($hosts[$k]);
			}
			}
		}
		$this->set('hosts',$hosts);
		$this->set('task',$taskInfo['Task']);
		$this->render('admin_index','ajax');
	}
	
	
	function admin_index($tid=0){
		
		
		//get filter field		
		$tid=intval($tid);
		if($tid>0){
			//clear
			$this->Session->delete($this->uses[0].'.host_id');
		}
		if($tid==0)$tid=intval($this->Session->read($this->uses[0].'.task_id'));
		
		$taskInfo=$this->getPermission($tid);
		
		if(empty($taskInfo)){
			$this->Session->write('error',_resource('you have not permission',true));
			if($this->Session->read('CurrentModule')=='Task')
				$this->redirectAjaxTo('tasks/lists','listContent');
			else
				$this->redirectAjaxTo('homes/lists','listContent');
		}
		$this->Session->write($this->uses[0].'.task_id',$tid);  
		
		//get source control
		$sc=$this->SourceControl->find('first',array('conditions'=>array('project_id'=>$taskInfo['Project']['Project']['id'],'active'=>1)));
		if(!empty($sc)){
			//$reval=shell_exec('~/svn_search.sh '.$taskInfo['Task']['Task']['taskcode'].' https://itk-taskman.googlecode.com/svn/ ./repo/itk-taskman duyhph@gmail.com');
			$repoPath='./repo/'.$taskInfo['Project']['Project']['code'];
			$reval=shell_exec('~/svn_search.sh '.$taskInfo['Task']['Task']['taskcode'].' '.$sc['SourceControl']['url'].' '.$repoPath.' --username '.$sc['SourceControl']['username']);
						$files=array();
			foreach(explode("\n",$reval) as $k=>$v){
				$fileinfo=explode(":",$v);
				//check if file is directory:
				//t($repoPath.$fileinfo,0);
				//t(is_dir($repoPath.$fileinfo[0]));
				if(count($fileinfo)==4 && !array_key_exists($fileinfo[0],$files) && !is_dir($repoPath.$fileinfo[0])){
					$files[$fileinfo[0]]=$fileinfo;
				}
			}
			$this->Session->write('filedeploys',$files);
			//get host
			$hosts=$this->Host->find('all',array('conditions'=>'Host.published = 1 and Host.project_id ='.$taskInfo['Project']['Project']['id']));
			//check permit
			if(!empty($hosts)){
			foreach($hosts as $k=>$v){		
				if($v['Host']['user_id']== $this->user['id'] || $this->checkUserInString($v['Host']['users']))
					$hosts[$v['Host']['id']]=$v['Host']['name'];
				unset($hosts[$k]);
			}
			}
		}
		$this->set('hosts',$hosts);
		$this->set('task',$taskInfo['Task']);
		$this->render('admin_index','ajax');
	}
	
	
	function admin_lists(){
		//get filter field		
		
		$tid=intval($this->Session->read($this->uses[0].'.task_id'));
		$taskInfo=$this->getPermission($tid);
		if(empty($taskInfo)){
			$this->Session->write('error',_resource('you have not permission',true));
			if($this->Session->read('CurrentModule')=='Task')
				$this->redirectAjaxTo('tasks/lists','listContent');
			else
				$this->redirectAjaxTo('homes/lists','listContent');
		}		
		$files=$this->Session->read('filedeploys');
		//get host
		$hostid=$this->Session->read($this->uses[0].'.host_id');
		$this->Deploy->recursive=2;
		$data=$this->Deploy->find('list',array('conditions'=>array('Deploy.host_id'=>$hostid,'Deploy.project_id'=>$taskInfo['Project']['Project']['id']),'fields'=>array('Deploy.file','Deploy.version')));
		if($hostid>0){
			foreach($files as $k=>$v){
				if(isset($data[$k]))$files[$k][]=$data[$k];
				else $files[$k][]=0;
			}
		}
		
		$this->set('data0',$files);
		$this->set('task',$taskInfo['Task']);
		$this->render('admin_lists','ajax');
	}
	
	function admin_host($id){		
		$this->Session->write($this->uses[0].'.host_id',intval($id));
		$this->admin_lists();
	}
	
	function admin_push(){			
		
		
		$tid=intval($this->Session->read($this->uses[0].'.task_id'));
		$taskInfo=$this->getPermission($tid);		
		if(empty($taskInfo)){
			$this->Session->write('error',_resource('you have not permission',true));
			if($this->Session->read('CurrentModule')=='Task')
				$this->redirectAjaxTo('tasks/lists','listContent');
			else
				$this->redirectAjaxTo('homes/lists','listContent');
		}
		//get host
		$hostid=$this->Session->read($this->uses[0].'.host_id');
		//get file
		$files=$this->Session->read('filedeploys');
		//check host permission
		$host=$this->Host->read(null,$hostid);
		$error=false;
		if(empty($host) || !$this->checkUserInString($host['Host']['users']) || empty($files)){
			$error=true;
			$this->Session->write('error',_resource('you have not permission',true));
		}
		
		//connect to host
		if(!$error){
			// set up basic connection
			$conn_id = ftp_connect($host['Host']['hostname']);
			if($conn_id){
				// login with username and password
				if(!@ftp_login($conn_id, $host['Host']['username'], $host['Host']['password'])){
					$error=true;
					$this->Session->write('error',_resource('cannot login to host '.$host['Host']['name'].' with username='.$host['Host']['username'],true));
				}
				
			}
			else{
				$error=true;
				$this->Session->write('error',_resource('cannot connect to host '.$host['Host']['name'],true));
			}
			
			
			//ftp_mkdir($conn_id, 'ddd');
			
			//ftp_chmod($conn_id, 0777, 'ddd') ;
		}
		
		if(!$error){
			//begin push==============	
			//get mappath
			substr($host['Host']['mapto'],0,1)=='/'?$mapto=$host['Host']['mapto']:$mapto='/'.$host['Host']['mapto'];
			substr($mapto,-1)=='/'?$mapto=substr($mapto,0,strlen($mapto)-1):1;
			substr($host['Host']['mapfrom'],0,1)=='/'?$mapfrom=$host['Host']['mapfrom']:$mapfrom='/'.$host['Host']['mapfrom'];
			foreach($files as $k=>$v)
			{				
				$filepath=$k;
				if(substr($k,0,strlen($mapfrom))==$mapfrom)$filepath=substr($k,strlen($mapfrom));				
				//remove /
				substr($filepath,0,1)=='/'?$filepath=substr($filepath,1,strlen($filepath)):1;
				//check path and create path
				if(strlen($mapto)>0)$current_path='/';
				else $current_path='.';
				$arraypaths=explode('/',$filepath);
				//t($arraypaths);
				$data=$this->Deploy->find('list',array('conditions'=>array('Deploy.host_id'=>$hostid,'Deploy.project_id'=>$taskInfo['Project']['Project']['id']),'fields'=>array('Deploy.file','Deploy.version')));
				if(!isset($data[$k]) || $data[$k]!=$v[3]){

					foreach($arraypaths as $k1=>$v1){
						//check file or directory
						if($k1<count($arraypaths)-1){						
							
							//check file exist
							$contents_on_server = ftp_nlist($conn_id, $mapto.$current_path);
							//t($mapto.$current_path,0);
							//t($contents_on_server,0);
							//t($current_path.'/'.$v1,0);
							//t($arraypaths);
							if (!in_array($v1, $contents_on_server) && !in_array(substr($current_path,2,strlen($current_path)).'/'.$v1, $contents_on_server)){
								//create dir			
								//t($mapto.$current_path,0);
								//t($$current_path.'/'.$v1);							
								if($v[1]=="D"){@ftp_rmdir($conn_id, $mapto.$current_path.'/'.$v1);}
								else{ftp_mkdir($conn_id, $mapto.$current_path.'/'.$v1);ftp_chmod($conn_id, 0755, $mapto.$current_path.'/'.$v1) ;}
							}
							
							$current_path.='/'.$v1;
							
						}
						else{
							//push file to server
							//t('./repo/'.$taskInfo['Project']['Project']['code'].$k);
							
							if($v[1]=="D")@ftp_delete($conn_id, $mapto.$current_path.'/'.$v1);
							else ftp_put($conn_id, $mapto.$current_path.'/'.$v1,'./repo/'.$taskInfo['Project']['Project']['code'].$k , FTP_BINARY);
						}
						
					}
				}
				
				//save version into db
				
				if(isset($data[$k])){
					//update
					$this->Deploy->updateAll(array('Deploy.version'=>$v[3]),array('Deploy.host_id'=>$hostid,'Deploy.project_id'=>$taskInfo['Project']['Project']['id'],'Deploy.file'=>$k));
				}
				else{
					//insert
					$this->Deploy->create(array('file'=>$k,'version'=>$v[3],'host_id'=>$hostid,'project_id'=>$taskInfo['Project']['Project']['id']));
					$this->Deploy->save();
				}
				//$this->Deploy->find('first')
			}
			
			
			
			$this->Session->write('message',_resource('push successful',true));
		}
		ftp_close($conn_id); 
		$this->admin_lists();
	}

	
	

}
?>
